<!--
 * @Author: zjf
 * @Date: 2023-11-28 21:21:25
 * @LastEditors: zjf
 * @LastEditTime: 2023-12-09 18:07:23
 * @Description: 阶段 form组件
-->
<template>
  <div class="l-rblock l-form-viewer" style="padding:5px 10px 50px 20px">
    <div class="l-auto-window">
      <el-tabs v-model="activeName" type="card" :before-leave="handleTabBeforeLeave">
        <el-tab-pane class="l-tabs-container" :label="$t('基本信息')" name="tab0">
          <el-form :model="formData" :rules="rules" size="mini" labelPosition="top" labelWidth="110px" ref="form">
            <l-custom-form ref="CustomForm" :disabled="disabled" :columns="columns"></l-custom-form>
          </el-form>
        </el-tab-pane>
        <el-tab-pane class="l-tabs-container" :label="$t('文件资料')" name="tab2">
          <l-file-management v-if="activeName == 'tab2' && projectId" :projectId="projectId"
            :businessCode="businessCode" :businessId="stageId"></l-file-management>
        </el-tab-pane>
      </el-tabs>
      <div class="tab-btn">
        <el-button size="small" @click="handleClose">关闭</el-button>
        <template v-if="activeName == 'tab0' && !disabled">
          <el-button v-if="stageId" size="small" type="primary" @click="handleSave(true)"> 更新</el-button>
          <el-button v-else size="small" type="primary" @click="handleSave(false)">提交 </el-button>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'l-process-form',
  components: {
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    config: Object
  },
  data() {
    return {
      fromEditing: false,
      activeName: 'tab0',

      projectId: "", // 项目id
      stageId: "", // 阶段id

      // 表单信息
      formData: {},
      rules: {},
      columns: [],
      businessCode: '',
    };
  },
  created() {
    this.formData = this.$deepClone(this.config.formData)
    this.rules = this.$deepClone(this.config.rules)
    this.columns = this.$deepClone(this.config.formColmuns)
    this.businessCode = this.$deepClone(this.config.businessCode)
  },
  computed: {
  },
  mounted() {

    this.lr_loadDataItem('constructionNature') // 建设性质
    this.lr_loadDataItem('projectLevel') // 项目等级
    this.lr_loadDataItem('trueOrFalse') // 是否
    this.lr_loadDataItem('worksCategory') // 工程类别
    this.lr_loadDataItem('subordinatePlate') // 所属区域
    this.lr_loadDataItem('contractType') // 合同类别
    this.lr_loadDataSourceData('businessStage', false) // 项目阶段业务
    this.lr_loadDataItem('overallProjectPhase') // 项目总体阶段
    this.lr_loadDataItem('constructionStage') // 施工阶段
    this.init()

  },
  methods: {
    init() {

      this.$refs.CustomForm.formData = this.formData
    },

    // 重置表单
    resetForm() {
      this.$formClear(this.$refs.form)
      this.activeName = 'tab0'
      Object.assign(this.$data, this.$options.data())
      this.$refs.CustomForm.formData = {}
    },
    // 校验表单
    async validateForm() {
      if (!await this.$formValidateWraper(this.$refs.form)) {
        return false
      }
      return true
    },

    // 获取当前表单数据
    getForm() {
      this.formData = this.$refs.CustomForm.formData
      return {
        projectId: this.projectId,
        stageCode: this.config.stageCode,
        businessCode: this.config.businessCode,
        ...this.formData
      }
    },
    /** 加载项目阶段信息   初始化表单 */
    async loadFormData(info) {
      this.projectId = info.projectId
      this.stageId = info.id
      this.fromEditing = true
      const data = await this.$awaitWraper(this.config.api.get(info.id))
      if (data) {
        // 项目信息
        for (const key in this.formData) {
          if (info[key]) {
            this.formData[key] = info[key] || null;
          }
          if (Object.prototype.hasOwnProperty.call(data, key)) {
            if (typeof data[key] === 'boolean') {
              data[key] = data[key].toString();
            }
          }
          this.formData[key] = data[key] || this.formData[key];
        }
        this.$refs.CustomForm.formData = this.formData
        return true
      } else {
        return false
      }
    },

    /** 关闭表单 */
    handleClose() {
      this.resetForm()
      this.$emit('close')
    },
    /** 提交 保存 事件 */
    async handleSave(isEdit) {
      if (await this.validateForm()) {
        const res = await this.saveForm(isEdit)
        if (res) {
          this.$message({
            type: 'success',
            message: '提交成功'
          })
          this.$emit('refresh')
          this.stageId = this.stageId || res.id
          this.initDir()
        }
      }
    },
    /** 保存表单数据 */
    async saveForm(isEdit) {
      let postData = this.getForm()
      if (isEdit) {// 编辑
        return await this.$awaitWraper(this.config.api.update(this.stageId, postData))
      } else { // 新增
        return await this.$awaitWraper(this.config.api.add(postData))
      }
    },

    /** 表单切换校验 */
    handleTabBeforeLeave(activeName, oldActiveName) {
      // 判断业务id是否存在 即当前业务信息是否为编辑状态
      if (this.stageId == '') {
        return new Promise((resolve, reject) => {
          if (oldActiveName == 'tab0') {
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.$message({
                  message: '请点击提交完成新增！',
                  type: 'warning'
                });
                reject()
              }
              else {
                this.$message({
                  message: '请先填写完整信息！',
                  type: 'warning'
                });
                reject()
              }
            })
          }
          else {
            reject()
          }
        })
      }
    },

    /** 文件夹初始化 */
    async initDir() {
      const params = {
        projectId: this.projectId,
        businessId: this.stageId,
        parentId: this.stageId,
        configBusinessId: this.config.businessCode
      }
      const data = await this.$awaitWraper(window.$crud("project/businness/archives/schema").getInfo(params))
      if (data.length == 0) {

        await this.$awaitWraper(window.$crud("project/businness/init/dir").getInfo(params))
      }


    },



  }
}
</script>
<style lang="scss" scoped>
.l-auto-window {
  // height: calc(100% - 50px);
  height: 100%;
}

.tab-btn {
  position: absolute;
  bottom: -40px;
  right: 0px;
}

.l-tabs-container {
  padding-top: 16px !important;
}

.tabs-map {
  overflow-y: hidden !important;
}
</style>